package znbkBkfx.BKFX_TKT;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.BaseRecyclerAdapter;
import com.example.znbk.znbklibrary.base.BaseRecyclerViewHolder;
import com.example.znbk.znbklibrary.util.LancooUtils;
import com.example.znbk.znbklibrary.widget.CustomEditText;
import com.example.znbk.znbklibrary.widget.ScaleButton;
import com.lancoo.znbkxx.R;
import com.tt.CoreType;
import com.tt.QType;
import com.tt.SkEgnManager;
import com.tt.listener.OnRecordListener;
import com.tt.widget.AudioRecoderUtils;
import com.tt.widget.JSONTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;

import znbkBkfx.GetBkfxJson.BkfxPaperEntity;

public class BkfxTktAnswerAdapter extends BaseRecyclerAdapter {

    private int TotalItemCount = -1;
    private int SubmitState = -1;
    private void getAnswerInfor(){
        TotalItemCount = bkfxPaperEntity.getQuesList().get(quesiIndex).getTotalItemCount();
        SubmitState = bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getSubmitState();
    }


    private Context context;
    private BkfxPaperEntity bkfxPaperEntity;
    private int quesiIndex = -1;
    private LayoutInflater inflater;

    public BkfxTktAnswerAdapter(Context context, BkfxPaperEntity bkfxPaperEntity, int quesiIndex){
        this. context=context;
        this.bkfxPaperEntity = bkfxPaperEntity;
        this.quesiIndex = quesiIndex;
        inflater=LayoutInflater. from(context);
        getAnswerInfor();
    }

    @Override
    public int getItemCount() {
        return TotalItemCount;
    }

    @Override
    public long getItemId(int position){
        return position;
    }

    private int RecordPosition = -1;
    private TextView mTvQuesNumber;
    private CustomEditText mCedtWriteAnswer;
    private ScaleButton mSBtnRecordAnswer;
    @Override
    public View getHolderView(ViewGroup parent, int position) {
        View view = inflater.inflate(R.layout.bkfx_adapter_item_answer_tkt,parent, false);
        return view;
    }

    private LinearLayout mLlOption;
    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder baseRecyclerViewHolder, final int position) {
        mLlOption = baseRecyclerViewHolder.getView(R.id.ll_option);
        //显示小题题号
        int SortIndex = -1;
        String GenreName = bkfxPaperEntity.getQuesList().get(quesiIndex).getGenreInfo().getGenreName();
        if(GenreName.equals("选词填空")){
             SortIndex = bkfxPaperEntity.getQuesList().get(quesiIndex).getChildList().
                    get(position).getSubChildList().get(0).getSubChildItem().get(0).getSortIndex();
        }else{
             SortIndex = bkfxPaperEntity.getQuesList().get(quesiIndex).getChildList().
                    get(0).getSubChildList().get(0).getSubChildItem().get(position).getSortIndex();
        }
        mTvQuesNumber = baseRecyclerViewHolder.getView(R.id.tv_quesNumber);
        mTvQuesNumber.setText(String.valueOf(SortIndex)+".");

        //显示输入框内容（包括对错判断）
        mCedtWriteAnswer = baseRecyclerViewHolder.getView(R.id.cedt_writeAnswer);
        mCedtWriteAnswer.clearFocus();
        if(GenreName.equals("选词填空")){
            mCedtWriteAnswer.setText(bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().get(position).
                    getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer());
        }else{
            mCedtWriteAnswer.setText(bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().get(0).
                    getSubChildList().get(0).getSubChildItem().get(position).getStuAnswer());
        }
        if(SubmitState==2){
            mCedtWriteAnswer.setFocusable(false);
        }else{
            mCedtWriteAnswer.setFocusable(true);
        }
        mCedtWriteAnswer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e("=afterTextChanged==",position+"=====================afterTextChanged======================"+s.toString());
                String stuAnswer = s.toString().trim();
                int SubmitState = bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getSubmitState();
                if(SubmitState!=2) {
                    String GenreName = bkfxPaperEntity.getQuesList().get(quesiIndex).getGenreInfo().getGenreName();
                    if(GenreName.equals("选词填空")){
                        bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().
                                get(position).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer(stuAnswer);
                    }else{
                        bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().
                                get(0).getSubChildList().get(0).getSubChildItem().get(position).setStuAnswer(stuAnswer);
                    }
                }
            }
        });


        if (RecordPosition == position){
            if(GenreName.equals("选词填空")){
                mCedtWriteAnswer.setText(bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().get(RecordPosition).
                        getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer());
            }else{
                mCedtWriteAnswer.setText(bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().get(0).
                        getSubChildList().get(0).getSubChildItem().get(RecordPosition).getStuAnswer());
            }
        }


        if(SubmitState==2){
            String StuAnswer = "";
            String ItemAnswer = "";
            if(GenreName.equals("选词填空")){
                 StuAnswer = bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().
                        get(position).getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer();
                 ItemAnswer = bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().
                        get(position).getSubChildList().get(0).getSubChildItem().get(0).getItemAnswer().trim();
            }else{
                 StuAnswer = bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().
                        get(0).getSubChildList().get(0).getSubChildItem().get(position).getStuAnswer();
                 ItemAnswer = bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().
                        get(0).getSubChildList().get(0).getSubChildItem().get(position).getItemAnswer().trim();
            }

            Log.e("==SubmitStateAA==","==编号=="+position+"==========StuAnswer============"+StuAnswer);
            Log.e("==SubmitStateAA==","==编号=="+position+"==========ItemAnswer==========="+ItemAnswer);
            String[] ItemAnswerArray = LancooUtils.returnArray(ItemAnswer,"$/",2);
            List<String> list=Arrays.asList(ItemAnswerArray);
            if(list.contains(StuAnswer)){
                mCedtWriteAnswer.setText(StuAnswer);
                mCedtWriteAnswer.setTextColor(Color.parseColor("#00b30d"));
                // 使用代码设置drawableleft
                Drawable drawableRight = context.getResources().getDrawable(R.mipmap.image_tk_result_right);
                // / 这一步必须要做,否则不会显示.
                drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),drawableRight.getMinimumHeight());
                mCedtWriteAnswer.setCompoundDrawables(null,null,drawableRight,null);
            }else{
                ItemAnswer = ItemAnswer.replaceAll("\\$","");
                if(StuAnswer.equals("")){
                    mCedtWriteAnswer.setText(Html.fromHtml(context.getResources().
                            getString(R.string.studentanswer_and_itemanswer,"未作答",ItemAnswer)));
                }else{
                    mCedtWriteAnswer.setText(Html.fromHtml(context.getResources().
                            getString(R.string.studentanswer_and_itemanswer,StuAnswer,ItemAnswer)));
                }
                // 使用代码设置drawableleft
                Drawable drawableRight = context.getResources().getDrawable(R.mipmap.image_tk_result_wrong);
                // / 这一步必须要做,否则不会显示.
                drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),drawableRight.getMinimumHeight());
                mCedtWriteAnswer.setCompoundDrawables(null,null,drawableRight,null);
            }
        }else{
            mCedtWriteAnswer.setCompoundDrawables(null,null,null,null);
        }

        //实现语音输入
        mSBtnRecordAnswer = baseRecyclerViewHolder.getView(R.id.sbtn_recordAnswer);
        if(SubmitState==2){
            mSBtnRecordAnswer.setBackgroundResource(R.mipmap.button_record_dark);
            mSBtnRecordAnswer.setFocusable(false);
            mSBtnRecordAnswer.setClickable(false);
        }else{
            mSBtnRecordAnswer.setBackgroundResource(R.mipmap.button_record_light);
            mSBtnRecordAnswer.setFocusable(true);
            mSBtnRecordAnswer.setClickable(true);
        }

        mSBtnRecordAnswer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if(SubmitState!=2) {
                            Log.e("mSBtnRecordAnswer", "===============点击了==============" + position);
                            mRecoderUtils = new AudioRecoderUtils();
                            SkEgnManager.getInstance(context).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                            mRecoderUtils.startRecord();
                            RecordPosition = position;
                        }
                        return true;
                    case MotionEvent.ACTION_UP:
                        if(SubmitState!=2) {
                            mRecoderUtils.stopRecord();
                        }
                        return true;
                    case MotionEvent.ACTION_CANCEL:
                        if(SubmitState!=2) {
                            mRecoderUtils.stopRecord();
                        }
                        return true;
                }
                return false;
            }
        });


        int SubmitState = bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getSubmitState();
        if(SubmitState==2){
            mLlOption.removeAllViews();
        }else {
            if (position == TotalItemCount - 1) {
                mLlOption.removeAllViews();
                View mView = new View(context);
                mView.setBackgroundColor(Color.parseColor("#ffffff"));
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 200);
                mLlOption.addView(mView, lp);
            }
        }

    }

    /********************************************************/
    private AudioRecoderUtils mRecoderUtils;
    private String  mCoreType = CoreType.EN_ASR_REC;
    /*
     * 话咪录音操作
     * */
    OnRecordListener mOnRecordListener = new OnRecordListener() {
        @Override
        public void onRecordStart() {
            //开始录制
//            Log.e("==onRecordingAA==","========vad_status==========="+"121212121212");
        }
        @Override
        public void onRecording(int vad_status, int sound_intensity) {
            //录制中
            Log.e("==onRecordingAA==","========vad_status==========="+vad_status);
            Log.e("==onRecordingBB==","=========sound_intensity==========="+sound_intensity);
            if(vad_status==2){
                SkEgnManager.getInstance(context).stopRecord();
                mRecoderUtils.stopRecord();
            }
        }
        @Override
        public void onRecordEnd(String result) {
            //录制结束
            try {
                final JSONObject json = new JSONObject(result);
                Log.e("17kouyuAAA", "返回json===>" + result);
                String speakResult = "";
                if(!getResult(result).equals("")) {
                    speakResult = getResult(result);
                }
                Log.e("==AAGGFF==","========VVVVVVKKKKK》》==========="+speakResult);
                if(!speakResult.equals("")) {

                    String GenreName = bkfxPaperEntity.getQuesList().get(quesiIndex).getGenreInfo().getGenreName();
                    if(GenreName.equals("选词填空")){
                        bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().get(RecordPosition).getSubChildList().get(0).
                                getSubChildItem().get(0).setStuAnswer(speakResult);
                        Log.e("==mSBtnRecordAnswer==","========选词填空==========="+speakResult);
                    }else{
                        bkfxPaperEntity.getPaperAnswer().get(quesiIndex).getChildList().get(0).getSubChildList().get(0).
                                getSubChildItem().get(RecordPosition).setStuAnswer(speakResult);
                        Log.e("==mSBtnRecordAnswer==","========其他填空==========="+speakResult);
                    }

                    doRefresh(RecordPosition);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };


    private String getResult(String result) {

        String choiceSoundResult = "";
        StringBuilder keyValue = new StringBuilder();
        try{
            JSONObject returnObj = new JSONObject(result);
            JSONObject resultJSONObject = returnObj.getJSONObject("result");
            if(resultJSONObject.has("overall")){
                keyValue.append("总    分: " + resultJSONObject.getString("overall") + "\n");
            }
            Log.e("getResultAAAAA", "====返回json========答案=========>" + resultJSONObject.getString("recognition"));
            choiceSoundResult = resultJSONObject.getString("recognition");

        }catch (Exception e){
            e.printStackTrace();
        }
        keyValue.append("\n");
        keyValue.append(JSONTool.stringToJSON(result));

        return choiceSoundResult;
    }
    /************************************************************/

    public void doRefresh(int position) {
        RecordPosition = position;
        notifyDataSetChanged();
    }

}
